package com.uniriho.lxr0860_printer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.PrintManager;
import android.print.PrinterId;
import android.print.pdf.PrintedPdfDocument;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.printer.command.CpclCommand;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class PrinterTest extends Activity {
    private UsbPrinter usbPrinter;//USB打印
    URI uri;
    UsbManager usbManager;
    private List<Bitmap> mlist;
    private int totalpages = 1;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
//        usbPrinter = UsbPrinter.getInstance();
//        usbPrinter.initPrinter(this);
//        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        findViewById(R.id.button_print).setOnClickListener(view -> {
//                USBPrinter();
            Log.i("zsm", "device 打印");
//                sendCpcl();
//                usbPrinter.write("hello word!!!".getBytes());
//                startActivityForResult( new Intent(PrinterTest.this, UsbDeviceList.class ), Constant.USB_REQUEST_CODE );
            File pdfPath = AppCacheUtils.getFile("test.pdf");
//            String path =  "/storage/emulated/0/test.docx"
            Log.i("zsm", "path:" + pdfPath.getAbsolutePath());
//            PrinterShareMgr.getInstance().printFile(PrinterTest.this,doc.getAbsolutePath());
////              ComponentName comp = new ComponentName("com.dynamixsoftware.printershare","com.dynamixsoftware.printershare.ActivityPrintPDF");
//            ComponentName comp = new ComponentName("com.dynamixsoftware.printershare", "com.dynamixsoftware.printershare.ActivityPrintDocuments");
//            Intent intent = new Intent();
//            intent.setComponent(comp);
//            intent.setAction("android.intent.action.VIEW");
////                intent.setType("application/pdf");
//            Uri uri = FileProvider.getUriForFile(PrinterTest.this, getPackageName() + ".provider", doc);
////                intent.setDataAndType(uri, "application/vnd.android.package-archive");
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                uri = FileProvider.getUriForFile(PrinterTest.this, "com.uniriho.lxr0860_printer.provider", doc);
//            } else {
//                uri = Uri.fromFile(doc);
//            }
//            Log.i("zsm", "uri:" + uri);
////                uri= Uri.parse(Uri.decode("content://com.uniriho.lxr0860_printer.provider/test_dest.pdf"));
////                intent.setData(uri);
//            intent.setDataAndType(uri, "application/pdf");
//            startActivity(intent);


            PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
            String jobName = getString(R.string.app_name) + " Document";
            PrintAttributes.Builder builder = new PrintAttributes.Builder();
            builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
            printManager.print(jobName, new PrintDocumentAdapter() {
                @Override
                public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
                    // Create a new PdfDocument with the requested page attributes
                     mPdfDocument = new PrintedPdfDocument(PrinterTest.this, newAttributes);
                    pageHeight = newAttributes.getMediaSize().ISO_A4.getHeightMils() * 72 / 1000; //设置尺寸
                    pageWidth = newAttributes.getMediaSize().ISO_A4.getWidthMils() * 72 / 1000;
                    // 响应取消请求
                    if (cancellationSignal.isCanceled()) {
                        callback.onLayoutCancelled();
                        return;
                    }

                    ParcelFileDescriptor mFileDescriptor = null;
                    PdfRenderer pdfRender = null;
                    PdfRenderer.Page page = null;
                    try {
                        mFileDescriptor = ParcelFileDescriptor.open(pdfPath, ParcelFileDescriptor.MODE_READ_ONLY);
                        if (mFileDescriptor != null)
                            pdfRender = new PdfRenderer(mFileDescriptor);

                        mlist = new ArrayList<>();

                        if (pdfRender.getPageCount() > 0) {
                            totalpages = pdfRender.getPageCount();
                            for (int i = 0; i < pdfRender.getPageCount(); i++) {
                                if(null != page)
                                    page.close();
                                page = pdfRender.openPage(i);
                                Bitmap bmp = Bitmap.createBitmap(page.getWidth()*2,page.getHeight()*2, Bitmap.Config.ARGB_8888);
                                page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                                mlist.add(bmp);
                            }
                        }
                        if(null != page)
                            page.close();
                        if(null != mFileDescriptor)
                            mFileDescriptor.close();
                        if (null != pdfRender)
                            pdfRender.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (totalpages > 0) {
                        PrintDocumentInfo.Builder builder = new PrintDocumentInfo
                                .Builder("code.pdf")
                                .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                                .setPageCount(totalpages); //构建文档配置信息

                        PrintDocumentInfo info = builder.build();
                        callback.onLayoutFinished(info, true);
                    } else {
                        callback.onLayoutFailed("Page count is zero.");
                    }
                }

                @Override
                public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
                    // Write the file to be printed
                    // For example, write a text file
//                    try {
//                        InputStream input = new FileInputStream(doc);
//                        OutputStream output = new FileOutputStream(destination.getFileDescriptor());
//                        byte[] buf = new byte[1024];
//                        int bytesRead;
//                        while ((bytesRead = input.read(buf)) > 0) {
//                            output.write(buf, 0, bytesRead);
//                        }
//                        callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
//                    } catch (FileNotFoundException e) {
//                        // Handle file not found error
//                        e.printStackTrace();
//                    } catch (IOException e) {
//                        // Handle IO exception
//                        e.printStackTrace();
//                    }

                    for (int i = 0; i < totalpages; i++) {
                        if (pageInRange(pageRanges, i)) //保证页码正确
                        {
                            PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder(pageWidth,
                                    pageHeight, i).create();
                            PdfDocument.Page page =
                                    mPdfDocument.startPage(newPage); //创建新页面

                            if (cancellationSignal.isCanceled()) { //取消信号
                                callback.onWriteCancelled();
                                mPdfDocument.close();
                                mPdfDocument = null;
                                return;
                            }
                            drawPage(page, i); //将内容绘制到页面Canvas上
                            mPdfDocument.finishPage(page);
                        }
                    }

                    try {
                        mPdfDocument.writeTo(new FileOutputStream(
                                destination.getFileDescriptor()));
                    } catch (IOException e) {
                        callback.onWriteFailed(e.toString());
                        return;
                    } finally {
                        mPdfDocument.close();
                        mPdfDocument = null;
                    }

                    callback.onWriteFinished(pageRanges);
                }
                private boolean pageInRange(PageRange[] pageRanges, int page) {
                    for (int i = 0; i < pageRanges.length; i++) {
                        if ((page >= pageRanges[i].getStart()) &&
                                (page <= pageRanges[i].getEnd()))
                            return true;
                    }
                    return false;
                }
                //页面绘制（渲染）
                private void drawPage(PdfDocument.Page page,int pagenumber) {
                    Canvas canvas = page.getCanvas();
                    if(mlist != null){
                        Paint paint = new Paint();
                        Bitmap bitmap = mlist.get(pagenumber);
                        int bitmapWidth = bitmap.getWidth();
                        int bitmapHeight = bitmap.getHeight();
                        // 计算缩放比例
                        float scale = (float)pageWidth/(float)bitmapWidth;
                        // 取得想要缩放的matrix参数
                        Matrix matrix = new Matrix();
                        matrix.postScale(scale, scale);
                        canvas.drawBitmap(bitmap,matrix,paint);
                    }
                }
                @Override
                public void onFinish() {
                    //完成打印过程
                    //例如关闭文件输出流
                    Log.i("zsm","打印完成");
                }
            }, builder.build());
        });

    }

    private int pageHeight;
    private int pageWidth;
    private PdfDocument mPdfDocument;
//    onLayout()方法的主要任务就是计算在新的设置下，需要打印的页数，如通过打印的方向决定页数：
//    private int computePageCount(PrintAttributes printAttributes) {
//        int itemsPerPage = 4; // default item count for portrait mode
//
//        PrintAttributes.MediaSize pageSize = printAttributes.getMediaSize();
//        if (!pageSize.isPortrait()) {
//            // Six items per page in landscape orientation
//            itemsPerPage = 6;
//        }
//
//        // Determine number of print items
//        int printItemCount = getPrintItemCount();
//
//        return (int) Math.ceil(printItemCount / itemsPerPage);
//    }

    //    @Override
//    protected void onStart()
//    {
//        super.onStart();
//        IntentFilter filter = new IntentFilter(Constant.ACTION_USB_PERMISSION );
//        filter.addAction( UsbManager.ACTION_USB_DEVICE_DETACHED );
//        filter.addAction( UsbManager.ACTION_QUERY_PRINTER_STATE );
//        filter.addAction( DeviceConnFactoryManager.ACTION_CONN_STATE );
//        filter.addAction( UsbManager.ACTION_USB_DEVICE_ATTACHED );
//        registerReceiver( receiver, filter );
//    }
//    private String			usbName;
//    @Override
//    protected void onActivityResult( int requestCode, int resultCode, Intent data )
//    {
//        super.onActivityResult( requestCode, resultCode, data );
//        if ( resultCode == RESULT_OK )
//        {
//            switch ( requestCode )
//            {
//
//                /*USB连接*/
//                case Constant.USB_REQUEST_CODE: {
//                    closeport();
//                    /* 获取USB设备名 */
//                    usbName = data.getStringExtra( UsbDeviceList.USB_NAME );
//                    /* 通过USB设备名找到USB设备 */
//                    UsbDevice usbDevice = Utils.getUsbDeviceFromName( PrinterTest.this, usbName );
//                    /* 判断USB设备是否有权限 */
//                    if ( usbManager.hasPermission( usbDevice ) )
//                    {
//                        usbConn( usbDevice );
//                    } else {        /* 请求权限 */
//                        PendingIntent  mPermissionIntent = PendingIntent.getBroadcast( this, 0, new Intent( Constant.ACTION_USB_PERMISSION ), 0 );
//                        usbManager.requestPermission( usbDevice, mPermissionIntent );
//                    }
//                    break;
//                }
//
//                default:
//                    break;
//            }
//        }
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (usbPrinter!=null) {
            usbPrinter.close();
        }

    }


    /**
     * 重新连接回收上次连接的对象，避免内存泄漏
     */
//    private void closeport()
//    {
//        if ( DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null &&DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort != null )
//        {
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel();
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort.closePort();
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort = null;
//        }
//    }

    /**
     * USB串口打印
     */
    private void USBPrinter() {
        // 设置加粗
        usbPrinter.bold(true);
        // 文字大小
        usbPrinter.setTextSize(3);
        // 设置文字居中
        usbPrinter.setAlign(1);
        // 打印文字并换行
        usbPrinter.printTextNewLine("结账单");
        // 取消加粗
        usbPrinter.bold(false);
        // 换2行
        usbPrinter.printLine(2);
        usbPrinter.setTextSize(0);
        // 设置文字居左对齐
        usbPrinter.setAlign(0);
        usbPrinter.printTextNewLine("流水号:20225301314");
        usbPrinter.printTextNewLine("单号:CF15545655454");
        usbPrinter.printTextNewLine("结账时间:2022/5/30");
        usbPrinter.printTextNewLine("收银员:***");
        // 换2行
        usbPrinter.printLine(1);
        usbPrinter.printTextNewLine("菜品       数量 重量    金额");
        usbPrinter.printTextNewLine("-------------------------------");
       /* for (int i = 0; i < addcpbean.size(); i++) {
            if (addcpbean.get(i).getName().length() == 1) {
                usbPrinter.printTextNewLine(addcpbean.get(i).getName() + "          " + addcpbean.get(i).getQuantity() + "   -     " + addcpbean.get(i).getSubtotal());
            } else if (addcpbean.get(i).getName().length() == 2) {
                usbPrinter.printTextNewLine(addcpbean.get(i).getName() + "        " + addcpbean.get(i).getQuantity() + "   -     " + addcpbean.get(i).getSubtotal());
            } else if (addcpbean.get(i).getName().length() == 3) {
                usbPrinter.printTextNewLine(addcpbean.get(i).getName() + "      " + addcpbean.get(i).getQuantity() + "   -     " + addcpbean.get(i).getSubtotal());
            } else if (addcpbean.get(i).getName().length() == 4) {
                usbPrinter.printTextNewLine(addcpbean.get(i).getName() + "    " + addcpbean.get(i).getQuantity() + "   -     " + addcpbean.get(i).getSubtotal());
            } else if (addcpbean.get(i).getName().length() == 5) {
                usbPrinter.printTextNewLine(addcpbean.get(i).getName() + "  " + addcpbean.get(i).getQuantity() + "   -     " + addcpbean.get(i).getSubtotal());
            } else {
                usbPrinter.printTextNewLine(addcpbean.get(i).getName());
                usbPrinter.printTextNewLine("            " + addcpbean.get(i).getQuantity() + "   -     " + addcpbean.get(i).getSubtotal());
            }
        }*/
        usbPrinter.printTextNewLine("-------------------------------");
        // 设置文字居右对齐
        usbPrinter.setAlign(0);
        usbPrinter.printTextNewLine("订单金额:￥200元");
        usbPrinter.printTextNewLine("优惠金额:￥50元");
        // 支付金额
        usbPrinter.printTextNewLine("支付金额:￥150元");
        usbPrinter.printTextNewLine("-------------------------------");
        usbPrinter.bold(true);
        // 文字大小
        usbPrinter.setTextSize(2);
        usbPrinter.printTextNewLine("备注：不要放辣椒，早点配送");
        // 换2行
        usbPrinter.printLine(2);
        // 文字大小
        usbPrinter.setTextSize(1);
        //居中
        usbPrinter.setAlign(1);
        usbPrinter.printTextNewLine("欢迎下次光临");
        usbPrinter.printLine(6);
        // 切纸
        usbPrinter.cutPager();
    }


    private void sendCpcl() {
        CpclCommand cpcl = new CpclCommand();
        cpcl.addInitializePrinter(1130, 1);
        cpcl.addJustification(CpclCommand.ALIGNMENT.CENTER);
        cpcl.addSetmag(1, 1);
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_4, 0, 30, "Sample");
        cpcl.addSetmag(0, 0);
        cpcl.addJustification(CpclCommand.ALIGNMENT.LEFT);
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_4, 0, 65, "Print text");
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_4, 0, 95, "Welcom to use our printer!");
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_13, 0, 135, "標籤打印機");
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_4, 0, 195, "打印");
        cpcl.addJustification(CpclCommand.ALIGNMENT.CENTER);
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_4, 0, 195, "网络");
        cpcl.addJustification(CpclCommand.ALIGNMENT.RIGHT);
//        cpcl.addText( CpclCommand.TEXT_FONT.FONT_4, 0, 195, "设备" );
//        cpcl.addJustification( CpclCommand.ALIGNMENT.LEFT );
//        cpcl.addText( CpclCommand.TEXT_FONT.FONT_4, 0, 230, "Print bitmap!" );
//        Bitmap bitmap = BitmapFactory.decodeResource( getResources(), R.drawable.printer);
//        cpcl.addEGraphics( 0, 255, 385, bitmap );
//        cpcl.addText( CpclCommand.TEXT_FONT.FONT_4, 0, 645, "Print code128!" );
//        cpcl.addBarcodeText( 5, 2 );
//        cpcl.addBarcode( CpclCommand.COMMAND.BARCODE, CpclCommand.CPCLBARCODETYPE.CODE128, 50, 0, 680, "SMARNET" );
//        cpcl.addText( CpclCommand.TEXT_FONT.FONT_4, 0, 775, "Print QRcode" );
//        cpcl.addBQrcode( 0, 810, "QRcode" );
//        cpcl.addJustification( CpclCommand.ALIGNMENT.CENTER );
        cpcl.addText(CpclCommand.TEXT_FONT.FONT_4, 0, 1010, "Completed");
        cpcl.addJustification(CpclCommand.ALIGNMENT.LEFT);
        cpcl.addPrint();
        Vector<Byte> datas = cpcl.getCommand();
        usbPrinter.printData(datas);
    }


    private DataOutputStream dataOutputStream;
    private DataInputStream dataInputStream;


    private void writeAttribute(final Integer tag, final String name, final String value) throws IOException {
        dataOutputStream.writeByte(tag);
        dataOutputStream.writeShort(name.length());
        dataOutputStream.write(name.getBytes());
        dataOutputStream.writeShort(value.length());
        dataOutputStream.write(value.getBytes());
    }

//    private String readStringValue() throws IOException {
//        byte[] valueBytes = dataInputStream.readNBytes(dataInputStream.readShort());
//        return new String(valueBytes, "us-ascii");
//    }
}
